import { connect } from 'node:net';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import { app, BrowserWindow } from 'electron';
import express from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';

// 禁用硬件加速
// app.disableHardwareAcceleration();

// 获取当前模块的目录名
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

let mainWindow; // 声明一个变量来存储主窗口
let serverPort; // 存储服务器端口

// 检查端口是否可用
function isPortAvailable(port) {
  return new Promise((resolve) => {
    const tester = connect({
      host: 'localhost',
      port,
    });

    tester.on('connect', () => {
      tester.end();
      resolve(false);
    });

    tester.on('error', (err) => {
      if (err.code === 'ECONNREFUSED') {
        resolve(true);
      } else {
        resolve(false);
      }
    });
  });
}

// 获取可用端口
async function getAvailablePort(startPort = 3000) {
  let port = startPort;
  while (!(await isPortAvailable(port))) {
    port++;
  }
  return port;
}

function createWindow() {
  mainWindow = new BrowserWindow({
    height: 1080,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      preload: path.join(__dirname, 'preload.mjs'),
    },
    width: 1920,
  });

  // 加载本地 Express 服务器
  mainWindow.loadURL(`http://localhost:${serverPort}`);

  // 打开开发者工具
  mainWindow.webContents.openDevTools();
}
app.whenReady().then(async () => {
  // 创建 Express 应用
  const expressApp = express();

  // 提供静态文件服务
  expressApp.use(express.static(path.join(__dirname, 'apps/web-antd/dist')));

  // 设置代理转发
  expressApp.use(
    '/prod-api',
    createProxyMiddleware({
      changeOrigin: true,
      target: 'http://localhost:8080', // 替换为你的后端服务器地址
    }),
  );

  // 添加通配符路由处理
  expressApp.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'apps/web-antd/dist/index.html'));
  });

  // 获取可用端口
  serverPort = await getAvailablePort();
  console.log(`Server starting on port ${serverPort}`);

  // 启动 Express 服务器
  expressApp.listen(serverPort, () => {
    console.log(`Server is running on http://localhost:${serverPort}`);
    createWindow();
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});
